package com.android.nearshop.app.activity.main;

import android.app.Activity;
import android.app.ActivityGroup;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.android.nearshop.R;
import com.android.nearshop.app.MyApplication;
import com.android.nearshop.app.activity.forum.ForumActivity;
import com.android.nearshop.app.activity.guesslike.GuessLikeActivity;
import com.android.nearshop.app.activity.memdate.MemDateActivity;
import com.android.nearshop.app.activity.setting.SettingActivity;
import com.android.nearshop.app.activity.shop.CheapActivity;
import com.android.nearshop.app.widget.IndexTabView;
import com.android.nearshop.business.cache.DataCacheManager;
import com.android.nearshop.business.location.MyBMapManager;
import com.android.nearshop.business.update.UpdateManager;
import com.android.nearshop.util.Constant;
import com.android.nearshop.util.CycledThread;
import com.android.nearshop.util.CycledThread.OnTimeoutListener;
import com.android.nearshop.util.ImageLoader;
import com.android.nearshop.util.ImageLoader.Imager;

/*********************************************************
 * @author : zhaohua
 * @version : 2012-8-13
 * @see : 主界面
 * @Copyright : copyrights reserved by personal 2007-2011
 **********************************************************/
public class MainIndexActivity extends ActivityGroup 
implements OnClickListener
{
    private static final String TAG = "MainIndexActivity";
    public static final int TAB_INDEX_0 = -1;
    public static final int TAB_INDEX_1 = 0;
    public static final int TAB_INDEX_2 = 1;
    public static final int TAB_INDEX_3 = 2;
    public static final int TAB_INDEX_4 = 3;
    public static final int TAB_INDEX_5 = 4;
    private static Animation shakeAnim;
    private FrameLayout mTabContentLayout;
    private IndexTabView[] mBottomTabs = new IndexTabView[5];
    private View index_indac;
    private int mTabIconsNormal[];
    private int mTabIconsSelected[];
    private int mCurTab = -2;
    private int mReqTab = TAB_INDEX_0;
    private MyBMapManager mMapManager;
    private CycledThread limitThread;
    private Bitmap kaijiBmp;
    
    public MainIndexActivity()
    {       
        mMapManager = MyBMapManager.getInstace(this);
        mTabIconsNormal = new int[5];
        mTabIconsNormal[0] = R.drawable.index_disshop_normal;
        mTabIconsNormal[1] = R.drawable.index_guslike_normal;
        mTabIconsNormal[2] = R.drawable.index_memdate_normal;
        mTabIconsNormal[3] = R.drawable.index_group_normal;
        mTabIconsNormal[4] = R.drawable.index_setting_normal;
        mTabIconsSelected = new int[5];
        mTabIconsSelected[0] = R.drawable.index_disshop_selected;
        mTabIconsSelected[1] = R.drawable.index_guslike_selected;
        mTabIconsSelected[2] = R.drawable.index_memdate_selected;
        mTabIconsSelected[3] = R.drawable.index_group_selected;
        mTabIconsSelected[4] = R.drawable.index_setting_selected;
//        DataCacheManager.getInstance().getAreaList(null);
//        DataCacheManager.getInstance().getCateList(null);        
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        setTheme(android.R.style.Theme_Translucent_NoTitleBar);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        handIntent();        
        mMapManager.startKeepLocation();
        if(MyApplication.getContext().isFirst)
        {
            checkLimit();
            showKaijiView();
//            UpdateManager.getInstacnce(this).checkUpdate(this,null);
        }else
        {
            showMainView();
        }
    }
    
    @Override
    protected void onResume()
    {
        super.onResume();
        if(mCurTab != -2 && mCurTab != mReqTab)
        {
            onTabClick(mReqTab);
        }
    }
    
    @Override
    protected void onNewIntent(Intent intent)
    {
        super.onNewIntent(intent);
        mReqTab = intent.getIntExtra(Constant.TAG_INDEX_TAB, mCurTab);
    }
    
    @Override
    protected void onDestroy()
    {
        // TODO ...
        super.onDestroy();       
    }
       
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	getMenuInflater().inflate(R.menu.main_menu, menu);//指定使用的XML
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
		case R.id.exit:
		{
			finish();
			MyApplication.getContext().exit();
			break;
		}
		default:
			break;
		}
    	
    	return true;
    }
    
    @Override
    public void onBackPressed()
    {
        if ((getCurrentActivity() instanceof ShakeShopActivity 
                || getCurrentActivity() instanceof SettingActivity)
                && ShakeShopActivity.isPopBack)
        {
            ShakeShopActivity.isPopBack = false;
            return;
        }
        AlertDialog.Builder builder = new Builder(this);
        builder.setMessage(R.string.exit_review);
        builder.setTitle(R.string.shortcut_notify);
        builder.setPositiveButton(R.string.sure,
                new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int which)
                    {
                        MainIndexActivity.super.onBackPressed();
                    }
                });

        builder.setNegativeButton(R.string.cancel,
                new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int which)
                    {
                        dialog.dismiss();
                    }
                });

        builder.create().show();
        return;
    }
        
    private void handIntent()
    {
        Intent it = getIntent();
        mReqTab = it.getIntExtra(Constant.TAG_INDEX_TAB, TAB_INDEX_0);
    }
    
    private void showKaijiView()
    {
        getWindow().setFlags(LayoutParams.FLAG_FULLSCREEN, LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_kai_ji_dong_hua);
        final String img = MyApplication.getContext().getStartImg();
        if(img == null)
        {
            // 还没更新启动广告
            findViewById(R.id.kaiji_lay).setBackgroundResource(R.drawable.kai_ji_dong_hua);
            // 获取动态更新的启动页面
//            DataCacheManager.getInstance().getStartAdv(null,false);
        }else
        {
            // 已更新           
//            new AsyncTask<Void, Void, Bitmap>()
//            {
//                @Override
//                protected Bitmap doInBackground(Void... params)
//                {                    
//                    return ImageLoader.getInstance().getBitmap(new Imager(img, null,0, 0));
//                }
//                protected void onPostExecute(Bitmap result) 
//                {
//                    ImageView imgView = (ImageView)findViewById(R.id.kaiji_lay);
//                    if(result != null)
//                    {
//                        kaijiBmp = result;
//                        if(imgView != null)
//                        {
//                            imgView.setImageBitmap(result);
//                        }
//                    }else
//                    {
//                    	if(imgView != null)
//                    	{
//                            imgView.setBackgroundResource(R.drawable.kai_ji_dong_hua);
//                    	}
//                    }
//                };
//            }.execute();
        }
    }
    
    private void showGuideView()
    {       
        final RelativeLayout floatView = (RelativeLayout)findViewById(R.id.float_layout);
        floatView.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                floatView.setVisibility(View.GONE);
            }
        });
        floatView.setVisibility(View.VISIBLE);
    }
    
    private void showMainView()
    {
        // 不是第一次进入，已显示主界面，返回
        if( !MyApplication.getContext().isFirst && mTabContentLayout != null)
        {          
            return;
        }
        if(kaijiBmp != null && !kaijiBmp.isRecycled())
        {
            kaijiBmp.recycle();
            kaijiBmp = null;
            Log.d(TAG, "realease kaiji bitmap");
        }
        // 进入主界面       
        getLocalActivityManager().removeAllActivities();
        disableFullScreen();
        setContentView(R.layout.activity_main_index);
        initMainViews();
        onTabClick(mReqTab);
        if(MyApplication.getContext().isNeedGuide())
        {
            showGuideView();
        }
    }
    
    private void disableFullScreen()
    {
      WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
      localLayoutParams.flags = ( (~LayoutParams.FLAG_FULLSCREEN) & localLayoutParams.flags);
      getWindow().setAttributes(localLayoutParams);
      getWindow().clearFlags(LayoutParams.FLAG_LAYOUT_NO_LIMITS);
      getWindow().setFlags(LayoutParams.FLAG_FULLSCREEN, (~LayoutParams.FLAG_FULLSCREEN));
    }
    
    private void initMainViews()
    {
        mTabContentLayout = (FrameLayout)findViewById(R.id.container);
        
        this.mBottomTabs[0] = ((IndexTabView)findViewById(R.id.tab1));
        this.mBottomTabs[0].setOnClickListener(this);
        this.mBottomTabs[1] = ((IndexTabView)findViewById(R.id.tab2));
        this.mBottomTabs[1].setOnClickListener(this);
        this.mBottomTabs[2] = ((IndexTabView)findViewById(R.id.tab3));
        this.mBottomTabs[2].setOnClickListener(this);
        this.mBottomTabs[3] = ((IndexTabView)findViewById(R.id.tab4));
        this.mBottomTabs[3].setOnClickListener(this);
        this.mBottomTabs[4] = ((IndexTabView)findViewById(R.id.tab5));
        this.mBottomTabs[4].setOnClickListener(this);
        for (int i = 0; i < this.mBottomTabs.length; i++)
        {
            this.mBottomTabs[i].setImageResource(mTabIconsNormal[i]);
        }
        this.index_indac = findViewById(R.id.index_indac);
    }

    private void onTabClick(int tabId)
    {
        Log.d(TAG, "onTabClick : mCurTab = "+mCurTab +" ,tabId = "+ tabId);
        if(mCurTab != -2 && mCurTab == tabId)
        {
            // 当前重复返回
            return;
        }else             
        {
            // 请求为当前
            if(tabId == -2 )
            {
                tabId = TAB_INDEX_0;
            }
            mCurTab = tabId;
            mReqTab = mCurTab;
        }
        onTabChanged(mCurTab);
        switch(mCurTab)
        {
            case TAB_INDEX_0:
            {
                showTab0();
                break;
            }
            case TAB_INDEX_1:
            {
                showTab1();
                break;
            }
            case TAB_INDEX_2:
            {
                showTab2();
                break;
            }
            case TAB_INDEX_3:
            {
                showTab3();
                break;
            }
            case TAB_INDEX_4:
            {
                showTab4();
                break;
            }
            case TAB_INDEX_5:
            {
                showTab5();
                break;
            }
        }
    }
    
    private void onTabChanged(int tabId)
    {
        for (int i = 0; i < this.mBottomTabs.length; i++)
        {
            this.mBottomTabs[i].reset(mTabIconsNormal[i]);
        }
        if(tabId >= 0)
        {
            this.index_indac.setVisibility(View.GONE);
            this.mBottomTabs[tabId].setClick();
            this.mBottomTabs[tabId].setImageResource(mTabIconsSelected[tabId]);
        }else
        {
            this.index_indac.setVisibility(View.VISIBLE);
        }
    }
    
    // 摇一摇主界面
    private void showTab0()
    {
        showTabContent("tab0",ShakeShopActivity.getStartActivity(this));
    }
    // 优惠商家
    private void showTab1()
    {
        showTabContent("tab1",new Intent(this,CheapActivity.class));
    }
    // 猜你喜欢
    private void showTab2()
    {
        showTabContent("tab2",new Intent(this,GuessLikeActivity.class));
    }
    // 会员日
    private void showTab3()
    {
    	showTabContent("tab3",new Intent(this,MemDateActivity.class));
    }
    // 社区
    private void showTab4()
    {
    	showTabContent("tab4",new Intent(this,ForumActivity.class));
    }
    // 设置 
    private void showTab5()
    {
        showTabContent("tab5",SettingActivity.getStartActivity(this));
    }
    
    private void showTabContent(String id, Intent subWindows)
    {
        if(subWindows == null) return;
        Window localWindow = getLocalActivityManager().startActivity(id, subWindows);
        mTabContentLayout.removeAllViews();
        mTabContentLayout.addView(localWindow.getDecorView());
    }
    
    // 显示 摇一摇 主界面
    public void gotoShake()
    {
        onTabClick(TAB_INDEX_0);
    }
    
    @Override
    public void onClick(View v)
    {
        switch(v.getId())
        {
            case R.id.tab1:
            {
                onTabClick(TAB_INDEX_1);
                break;
            }
            case R.id.tab2:
            {
                onTabClick(TAB_INDEX_2);
                break;
            }
            case R.id.tab3:
            {
                onTabClick(TAB_INDEX_3);
                break;
            }
            case R.id.tab4:
            {
                onTabClick(TAB_INDEX_4);
                break;
            }
            case R.id.tab5:
            {
                onTabClick(TAB_INDEX_5);
                break;
            }
        }
    }
   
    private void checkLimit()
    {
        if( limitThread == null)
        {
            limitThread = new CycledThread(200, 5000, new OnTimeoutListener()
            {
                @Override
                public void onTimeout()
                {
                    runOnUiThread(new Runnable()
                    {
                        public void run()
                        {
                            showMainView();
                        }
                    });
                }
            });
            limitThread.start();
        }
    }
    
    public static void startActivity(Context context, int tabIndex)
    {
        if(tabIndex < TAB_INDEX_0 || tabIndex > TAB_INDEX_5)
        {
            // 非法
            tabIndex = TAB_INDEX_0;
        }
        Intent it = new Intent(context, MainIndexActivity.class);
        it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        it.putExtra(Constant.TAG_INDEX_TAB, tabIndex);
        context.startActivity(it);
    }

    // 回到摇一摇主界面,如果view 不为null的话，摇晃一下才返回
    public static void gotoShake(final Activity activity, final View view)
    {
        if(view != null)
        {
            if(shakeAnim == null)
            {
                shakeAnim = AnimationUtils.loadAnimation(activity, R.anim.anim_shake);
            }
            view.startAnimation(shakeAnim);
            view.postDelayed(new Runnable()
            {
                @Override
                public void run()
                {
                    view.clearAnimation();
                    gotoShake(activity);
                }
            }, 500);
        }else
        {
            gotoShake(activity);
        }
    }
    
    private static void gotoShake(Activity activity)
    {
        if ( activity.getParent() != null && activity.getParent() instanceof MainIndexActivity)
        {
            ((MainIndexActivity)activity.getParent()).gotoShake();
        }else
        {
            MainIndexActivity.startActivity(activity, MainIndexActivity.TAB_INDEX_0);
            activity.finish();
        }
    }
}
